package org.xiyu.yee.onekeyminer_chainable_visual.client;

import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.neoforged.neoforge.client.gui.widget.ExtendedButton;
import net.neoforged.neoforge.client.gui.widget.ExtendedSlider;
import org.xiyu.yee.onekeyminer_chainable_visual.Config;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class ModernConfigScreen extends Screen {
    private final Screen parent;
    private final List<Object> configWidgets = new ArrayList<>();
    
    // 临时配置值
    private boolean tempShowMining;
    private boolean tempShowInteraction;
    private boolean tempOutlineMode;
    private boolean tempShowThroughWalls;
    private boolean tempShearingEnable;
    private boolean tempUseCustomRenderTypes;
    private double tempLineAlpha;
    private double tempHatchSpacing;
    private float[] tempColorMining = new float[4];
    private float[] tempColorInteract = new float[4];
    private float[] tempColorShearing = new float[4];
    
    // UI状态
    private int currentCategory = 0; // 0=显示, 1=颜色, 2=高级
    private Button categoryDisplayBtn;
    private Button categoryColorsBtn;
    private Button categoryAdvancedBtn;

    public ModernConfigScreen(Screen parent) {
        super(Component.translatable("text.autoconfig.onekeyminer_chainable_visual.title"));
        this.parent = parent;
        loadTempValues();
    }
    
    private void loadTempValues() {
        tempShowMining = Config.isShowMining();
        tempShowInteraction = Config.isShowInteraction();
        tempOutlineMode = Config.isOutlineMode();
        tempShowThroughWalls = Config.isShowThroughWalls();
        tempShearingEnable = Config.isShearingEnabled();
        tempUseCustomRenderTypes = Config.useCustomRenderTypes();
        tempLineAlpha = Config.getLineAlpha();
        tempHatchSpacing = Config.getHatchSpacing();
        
        // 复制颜色数组
        System.arraycopy(Config.getMiningColor(), 0, tempColorMining, 0, 4);
        System.arraycopy(Config.getInteractionColor(), 0, tempColorInteract, 0, 4);
        System.arraycopy(Config.getShearingColor(), 0, tempColorShearing, 0, 4);
    }

    @Override
    protected void init() {
        super.init();
        configWidgets.clear();
        
        int centerX = this.width / 2;
        
        // 类别标签页
        categoryDisplayBtn = new ExtendedButton(centerX - 120, 25, 80, 20, 
            Component.translatable("text.autoconfig.onekeyminer_chainable_visual.category.display"), 
            btn -> switchCategory(0));
        categoryColorsBtn = new ExtendedButton(centerX - 40, 25, 80, 20,
            Component.translatable("text.autoconfig.onekeyminer_chainable_visual.category.colors"), 
            btn -> switchCategory(1));
        categoryAdvancedBtn = new ExtendedButton(centerX + 40, 25, 80, 20,
            Component.translatable("text.autoconfig.onekeyminer_chainable_visual.category.advanced"), 
            btn -> switchCategory(2));
            
        addRenderableWidget(categoryDisplayBtn);
        addRenderableWidget(categoryColorsBtn);
        addRenderableWidget(categoryAdvancedBtn);
        
        // 初始化配置控件
        setupConfigWidgets();
        
        // 底部按钮
        addRenderableWidget(new ExtendedButton(centerX - 100, this.height - 35, 95, 20,
            Component.translatable("gui.done"), btn -> saveAndClose()));
        addRenderableWidget(new ExtendedButton(centerX + 5, this.height - 35, 95, 20,
            Component.translatable("gui.cancel"), btn -> onClose()));
    }
    
    private void switchCategory(int category) {
        if (currentCategory != category) {
            currentCategory = category;
            clearConfigWidgets();
            setupConfigWidgets();
        }
    }
    
    private void clearConfigWidgets() {
        configWidgets.forEach(widget -> {
            if (widget instanceof Button btn) {
                removeWidget(btn);
            } else if (widget instanceof ExtendedSlider slider) {
                removeWidget(slider);
            } else if (widget instanceof EditBox edit) {
                removeWidget(edit);
            }
        });
        configWidgets.clear();
    }
    
    private void setupConfigWidgets() {
        updateCategoryButtons();
        
        int centerX = this.width / 2;
        int startY = 60;
        int itemHeight = 25;
        
        switch (currentCategory) {
            case 0 -> setupDisplayCategory(centerX, startY, itemHeight);
            case 1 -> setupColorCategory(centerX, startY, itemHeight);
            case 2 -> setupAdvancedCategory(centerX, startY, itemHeight);
        }
    }
    
    private void updateCategoryButtons() {
        categoryDisplayBtn.active = currentCategory != 0;
        categoryColorsBtn.active = currentCategory != 1; 
        categoryAdvancedBtn.active = currentCategory != 2;
    }
    
    private void setupDisplayCategory(int centerX, int startY, int itemHeight) {
        int y = startY;
        
        // 显示挖掘高亮
        addCheckbox(centerX - 150, y, 300, Component.translatable("text.autoconfig.onekeyminer_chainable_visual.option.showMining"),
            tempShowMining, val -> tempShowMining = val);
        y += itemHeight;
        
        // 显示交互高亮
        addCheckbox(centerX - 150, y, 300, Component.translatable("text.autoconfig.onekeyminer_chainable_visual.option.showInteraction"),
            tempShowInteraction, val -> tempShowInteraction = val);
        y += itemHeight;
        
        // 剪羊毛高亮
        addCheckbox(centerX - 150, y, 300, Component.translatable("text.autoconfig.onekeyminer_chainable_visual.option.shearingEnable"),
            tempShearingEnable, val -> tempShearingEnable = val);
        y += itemHeight;
        
        // 轮廓模式
        addCheckbox(centerX - 150, y, 300, Component.translatable("text.autoconfig.onekeyminer_chainable_visual.option.outlineMode"),
            tempOutlineMode, val -> tempOutlineMode = val);
        y += itemHeight;
        
        // 穿墙显示
        addCheckbox(centerX - 150, y, 300, Component.translatable("text.autoconfig.onekeyminer_chainable_visual.option.showThroughWalls"),
            tempShowThroughWalls, val -> tempShowThroughWalls = val);
        y += itemHeight + 5;
        
        // 透明度滑条
        addSlider(centerX - 150, y, 300, Component.translatable("text.autoconfig.onekeyminer_chainable_visual.option.lineAlpha"),
            tempLineAlpha, 0.0, 1.0, val -> tempLineAlpha = val);
        y += itemHeight;
        
        // 填充间距滑条
        addSlider(centerX - 150, y, 300, Component.translatable("text.autoconfig.onekeyminer_chainable_visual.option.hatchSpacing"),
            tempHatchSpacing, 0.05, 1.0, val -> tempHatchSpacing = val);
    }
    
    private void setupColorCategory(int centerX, int startY, int itemHeight) {
        int y = startY;
        int colorHeight = 45;
        
        // 挖掘颜色
        addColorPicker(centerX - 150, y, Component.translatable("text.autoconfig.onekeyminer_chainable_visual.option.colorMining"),
            tempColorMining);
        y += colorHeight;
        
        // 交互颜色  
        addColorPicker(centerX - 150, y, Component.translatable("text.autoconfig.onekeyminer_chainable_visual.option.colorInteract"),
            tempColorInteract);
        y += colorHeight;
        
        // 剪羊毛颜色
        addColorPicker(centerX - 150, y, Component.translatable("text.autoconfig.onekeyminer_chainable_visual.option.colorShearing"),
            tempColorShearing);
    }
    
    private void setupAdvancedCategory(int centerX, int startY, int itemHeight) {
        int y = startY;
        
        // 自定义渲染类型
        addCheckbox(centerX - 150, y, 300, Component.translatable("text.autoconfig.onekeyminer_chainable_visual.option.useCustomRenderTypes"),
            tempUseCustomRenderTypes, val -> tempUseCustomRenderTypes = val);
    }
    
    private void addCheckbox(int x, int y, int width, Component text, boolean initialValue, Consumer<Boolean> onChange) {
        // 使用ExtendedButton代替Checkbox避免访问权限问题
        ExtendedButton button = new ExtendedButton(x, y, width, 20, 
            text.copy().append(": " + (initialValue ? "ON" : "OFF")), 
            btn -> {
                boolean newValue = !btn.getMessage().getString().endsWith("ON");
                onChange.accept(newValue);
                btn.setMessage(text.copy().append(": " + (newValue ? "ON" : "OFF")));
            });
        configWidgets.add(button);
        addRenderableWidget(button);
    }
    
    private void addSlider(int x, int y, int width, Component text, double initialValue, double min, double max, Consumer<Double> onChange) {
        ExtendedSlider slider = new ExtendedSlider(x, y, width, 20, text, Component.empty(), min, max, initialValue, false) {
            @Override
            protected void applyValue() {
                super.applyValue();
                onChange.accept(getValue());
            }
        };
        configWidgets.add(slider);
        addRenderableWidget(slider);
    }
    
    private void addColorPicker(int x, int y, Component label, float[] color) {
        // 颜色预览方块
        Button colorPreview = new ExtendedButton(x, y + 20, 40, 20, Component.empty(), btn -> {}) {
            @Override
            public void renderWidget(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) {
                int bgColor = 0xFF000000 | 
                    ((int)(color[0] * 255) << 16) | 
                    ((int)(color[1] * 255) << 8) | 
                    (int)(color[2] * 255);
                graphics.fill(this.getX(), this.getY(), this.getX() + this.width, this.getY() + this.height, bgColor);
                // 使用stroke绘制边框
                graphics.hLine(this.getX(), this.getX() + this.width - 1, this.getY(), 0xFFFFFFFF);
                graphics.hLine(this.getX(), this.getX() + this.width - 1, this.getY() + this.height - 1, 0xFFFFFFFF);
                graphics.vLine(this.getX(), this.getY(), this.getY() + this.height - 1, 0xFFFFFFFF);
                graphics.vLine(this.getX() + this.width - 1, this.getY(), this.getY() + this.height - 1, 0xFFFFFFFF);
            }
        };
        addRenderableWidget(colorPreview);
        configWidgets.add(colorPreview);
        
        // RGBA输入框
        String[] labels = {"R", "G", "B", "A"};
        for (int i = 0; i < 4; i++) {
            final int index = i;
            EditBox editBox = new EditBox(font, x + 50 + i * 55, y + 20, 50, 20, Component.literal(labels[i]));
            editBox.setValue(String.format("%.2f", color[i]));
            editBox.setResponder(text -> {
                try {
                    float value = Math.max(0f, Math.min(1f, Float.parseFloat(text)));
                    color[index] = value;
                } catch (NumberFormatException ignored) {}
            });
            addRenderableWidget(editBox);
            configWidgets.add(editBox);
        }
    }
    
    private void saveAndClose() {
        // 直接修改Config的静态字段（简单方法）
        Config.showMining = tempShowMining;
        Config.showInteraction = tempShowInteraction;
        Config.outlineMode = tempOutlineMode;
        Config.showThroughWalls = tempShowThroughWalls;
        Config.shearingEnable = tempShearingEnable;
        Config.useCustomRenderTypes = tempUseCustomRenderTypes;
        Config.lineAlpha = tempLineAlpha;
        Config.hatchSpacing = tempHatchSpacing;
        
        System.arraycopy(tempColorMining, 0, Config.colorMining, 0, 4);
        System.arraycopy(tempColorInteract, 0, Config.colorInteract, 0, 4);
        System.arraycopy(tempColorShearing, 0, Config.colorShearing, 0, 4);
        
        minecraft.setScreen(parent);
    }
    
    @Override
    public void onClose() {
        minecraft.setScreen(parent);
    }
    
    @Override
    public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) {
        this.renderBackground(graphics, mouseX, mouseY, partialTick);
        
        // 标题
        graphics.drawCenteredString(font, title, this.width / 2, 8, 0xFFFFFF);
        
        // 类别标题
        String categoryTitle = switch (currentCategory) {
            case 0 -> "text.autoconfig.onekeyminer_chainable_visual.category.display";
            case 1 -> "text.autoconfig.onekeyminer_chainable_visual.category.colors"; 
            case 2 -> "text.autoconfig.onekeyminer_chainable_visual.category.advanced";
            default -> "";
        };
        if (!categoryTitle.isEmpty()) {
            graphics.drawCenteredString(font, Component.translatable(categoryTitle), this.width / 2, 50, 0xCCCCCC);
        }
        
        // 绘制颜色选择器标签
        if (currentCategory == 1) {
            int y = 60;
            int colorHeight = 45;
            graphics.drawString(font, Component.translatable("text.autoconfig.onekeyminer_chainable_visual.option.colorMining"), 
                this.width / 2 - 150, y, 0xFFFFFF);
            y += colorHeight;
            graphics.drawString(font, Component.translatable("text.autoconfig.onekeyminer_chainable_visual.option.colorInteract"), 
                this.width / 2 - 150, y, 0xFFFFFF);
            y += colorHeight;
            graphics.drawString(font, Component.translatable("text.autoconfig.onekeyminer_chainable_visual.option.colorShearing"), 
                this.width / 2 - 150, y, 0xFFFFFF);
        }
        
        super.render(graphics, mouseX, mouseY, partialTick);
    }
}